# -*- coding: utf-8 -*-

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core import urlresolvers
from django.contrib.auth.models import User
from game.models import Ant, Base, UpholdReport
from django.conf import settings
import math # sólo para math.sqrt, mirar otras opciones


"""
    Apoyo
"""
class Uphold(models.Model):

    CH_STATUS = (
        ('P', u'Processing'), # En viaje
        ('F', u'Finished'), # Terminando
        ('U', u'Upholded'), # Apoyado
        ('B', u'Backed'), # Si conquistan o es destruido el hormiguero destino
        ('FB', u'Finished Backed'), # Finalizado tras volver.
        ('N', u'Null'), # Si cuando llega el apoyo han muerto todas las hormigas.
    )

    status = models.CharField(verbose_name=_(u'Status uphold'), max_length=3, blank=False, null=False, choices=CH_STATUS)
    base_finish = models.ForeignKey('game.Base', verbose_name=_(u"Base Finish"), blank=False, null=False, related_name='upholds_finish')
    base_start = models.ForeignKey('game.Base', verbose_name=_(u"Base Start"), blank=False, null=False, related_name='upholds_start')
    seconds = models.PositiveIntegerField(verbose_name=_(u'Seconds'), blank=True, null=True)
    date_created = models.DateTimeField(null=False, auto_now_add=True)
    date_updated = models.DateTimeField(null=False, auto_now=True)

    class Meta:
        app_label = 'game'
        verbose_name = _(u'Uphold')
        verbose_name_plural = _(u'Upholds')

    def __unicode__(self):
        return unicode(self.id) + u' -- ' + unicode(self.get_status_display())
    
    def save(self, ants=None, *args, **kwargs):
        if not self.pk: # Uphold initialized
            super(Uphold, self).save(*args, **kwargs)

            ants_base = self.base_start.ants_base.filter(player=self.base_start.player, position = 'C')

            self.ants_attach_to_uphold(ants_base.filter(type_ant = 'W'), ants['ant_0'])
            self.ants_attach_to_uphold(ants_base.filter(type_ant = 'OO'), ants['ant_1'])
            self.ants_attach_to_uphold(ants_base.filter(type_ant = 'OD'), ants['ant_2'])
            self.ants_attach_to_uphold(ants_base.filter(type_ant = 'FO'), ants['ant_3'])
            self.ants_attach_to_uphold(ants_base.filter(type_ant = 'FD'), ants['ant_4'])
            self.ants_attach_to_uphold(ants_base.filter(type_ant = 'Q'), ants['ant_5'])

            self.seconds = self.calculate_seconds()



                
        super(Uphold, self).save(*args, **kwargs)


    def resolve_back(self):
        ants = Ant.objects.filter(in_uphold = self)
        ants.update(in_uphold=None, position='C')
        self.status = 'FB'
        self.save()


    # Impacto del apoyo
    def resolve_uphold(self):
        
        self.status = 'F'
        ants = Ant.objects.filter(in_uphold = self)
    
        # Se actualiza el hormiguero porque ha podido haber cambios en el viaje
        self.base_finish = Base.objects.get(id = self.base_finish.id)
        self.base_finish.save()

        # Si no hacemos actualización, debería de tener siempre un nombre.
        try:
            name_start = self.base_start.player.name
        except:
            import pdb
            pdb.set_trace()
            if self.base_start.player:
                name_start = self.base_start.player.name
            else:
                name_start = u''

        if not self.base_finish.player: # Free Anthill
            self.status = 'B'
            name_finish = u''
            ants_uphold_finish = '0,0,0,0,0,0'
            info = _(u'El hormiguero ' + 
                        self.base_finish.get_coordinates_string() +
                        u' está desocupado. No hay movimiento de tropas.')

        elif ants.exists():
            if ants[0].player != self.base_finish.player: # Different player
                self.status = 'B'
                name_finish = unicode(self.base_finish.player.name)
                ants_uphold_finish = '0,0,0,0,0,0'
                info = _(u'El hormiguero ' +
                            self.base_finish.get_coordinates_string() +
                            u' pertenece al jugador ' +
                            self.base_finish.player.name +
                            u'. No hay movimiento de tropas.')

            else: # Ants uphold in Finish Base
                name_finish = self.base_finish.player.name
                ants.update(in_uphold=None, position='C', base=self.base_finish)
                self.status = 'U'
                ants_uphold_finish = self.comma_separated_ants(ants)
                info = _(u'El hormiguero ' +
                            self.base_finish.get_coordinates_string() +
                            u' ha sido apoyado.')

        ants_uphold_init = self.comma_separated_ants(ants)
        report = UpholdReport(uphold=self, ants_uphold_init=ants_uphold_init,
                    ants_uphold_finish=ants_uphold_finish,name_start=name_start,
                    name_finish=name_finish, info=info)
        report.save()
        self.save()
            
            
    # private
    def calculate_seconds(self):
        ants = Ant.objects.filter(in_uphold = self)
        diff_x = self.base_start.x_coordinate - self.base_finish.x_coordinate
        diff_y = self.base_start.y_coordinate - self.base_finish.y_coordinate
        hypotenuse = math.sqrt(pow(diff_x, 2) + pow(diff_y, 2))

        if ants.filter(type_ant = 'Q').exists():
            slow_speed = settings.SPEED[5]
        elif ants.filter(type_ant = 'W').exists():
            slow_speed = settings.SPEED[0]
        elif ants.filter(type_ant = 'OO').exists():
            slow_speed = settings.SPEED[1]
        elif ants.filter(type_ant = 'OD').exists():
            slow_speed = settings.SPEED[2]
        elif ants.filter(type_ant = 'FD').exists():
            slow_speed = settings.SPEED[4]
        elif ants.filter(type_ant = 'FO').exists():
            slow_speed = settings.SPEED[3]
        else:
            print "PROBLEMS"
            slow_speed = settings.SPEED[0]


        seconds = (hypotenuse * 60) / slow_speed # 60 seconds
        bonus_seconds = 0
        if self.base_start.player.bonus == 'S': # Bonus Player
            bonus_seconds += seconds * 0.1

        if self.base_start.player.bases.filter(bonus='S').exists(): # Bonus Base
            bonus_seconds += seconds * 0.1
        seconds = round(seconds - bonus_seconds)

        return seconds

    # private
    def ants_attach_to_uphold(self, ants, num_attached_ants):

        if num_attached_ants > ants.count():
            raise Exception(u'No tienes suficientes hormigas para éste movimiento de tropas.')

        index = 0
        for ant in ants:
            if index == num_attached_ants:
                break
            elif index < num_attached_ants:
                ant.in_uphold = self
                ant.position = 'M'
                ant.save()
                index += 1

    #private
    def comma_separated_ants(self, ants):
        ants_attack = ''
        ants_attack += str(ants.filter(type_ant='W').count())
        ants_attack += ','
        ants_attack += str(ants.filter(type_ant='OO').count())
        ants_attack += ','
        ants_attack += str(ants.filter(type_ant='OD').count())
        ants_attack += ','
        ants_attack += str(ants.filter(type_ant='FO').count())
        ants_attack += ','
        ants_attack += str(ants.filter(type_ant='FD').count())
        ants_attack += ','
        ants_attack += str(ants.filter(type_ant='Q').count())
        return ants_attack

